package cn.sunan.org.service.impl;

import cn.sunan.basic.config.service.impl.BesaServiceimpl;
import cn.sunan.basic.uitl.PageList;
import cn.sunan.org.domain.Department;
import cn.sunan.org.mapper.DepartmentMapper;
import cn.sunan.org.query.DepartmentQuery;
import cn.sunan.org.service.IDepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Transactional(readOnly = true,propagation = Propagation.SUPPORTS)
public class DepartmentServiceImpl extends BesaServiceimpl<Department> implements IDepartmentService {
    @Autowired
    private DepartmentMapper departmentMapper;
    @Resource
    private RedisTemplate redisTemplate;


    @Override
    @Transactional
    public void save(Department department) {

        departmentMapper.save(department);
        //设置dirPath
        this.update(department);
    }

    @Override
    @Transactional
    public void update(Department department) {
        //设置dirPath
        String dirPath = "";
        if(department.getParent()==null){
            //1.顶级部门: 取出自己的id直接拼接即可  (开启 : 获取自增主键)
            dirPath = "/"+department.getId();
        }else {
            //2.其他层级部门: 找到老爸的dirPath +"/" +自己的id
            Department parent = departmentMapper.selctById(department.getParent().getId());
            dirPath = parent.getDirPath()+"/"+department.getId();
        }
        department.setDirPath(dirPath);
        departmentMapper.update(department);
    }

    @Override
    public List<Department> queryTree() {
        if (redisTemplate.opsForValue().get("pageList")!=null){
                return (List<Department>) redisTemplate.opsForValue().get("pageList");
        }

        //1.方案1: 基于mybatis的1对多的思路,执行嵌套查询(不推荐)
        //2.方案2: 数据处理,在java中完成

        //1.查询出所有部门
        List<Department> departments = departmentMapper.selectAll();
        //把所有部门信息转为map: <部门id:部门对象>
        Map<Long, Department> map = new HashMap<>();
        for (Department d:departments){
            map.put(d.getId(),d);
        }
        //2.找出顶级部门
        List<Department> level1List = new ArrayList<>();
        for (Department dept:departments){
            if (dept.getParent_id()==null){
                level1List.add(dept);
            }else {
                //3.剩下的可能是 二级,三级,四级部门...
                //  找到当前部门的父级部门,把自己设置到他的 children 属性上
                Department parent = map.get(dept.getParent_id());
                if (parent!=null){
                    parent.getChildren().add(dept);
                }
            }
        }
        redisTemplate.opsForValue().set("pageList",level1List);
        return level1List;

    }
}
